package org.qloudgen.borg.pages.panel;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.qloudgen.borg.CommonValues;
import org.qloudgen.borg.beans.FileBean;
import org.qloudgen.borg.result.DataExportOperator;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class ExportPanel extends Panel {

	private static final long serialVersionUID = 1L;
	static Log log = LogFactory.getLog(ExportPanel.class);
	private boolean flag = false;
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
	
	public ExportPanel(String id,final FileBean fileBean, final List<String> headers,final String cacheID, final String sql, final ModalWindow window) {
		
		super(id);
		
		final RequiredTextField filePath = new RequiredTextField("filePath");
		
		final Form form = new Form("panel",new CompoundPropertyModel<FileBean>(fileBean.setFilePath(CommonValues.DEFAULT_EXPORT_DIR))) {

			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {
				
				FileBean fileBean = (FileBean) getDefaultModelObject();
				
				File file = new File(fileBean.getFilePath());
				
				if (!file.isDirectory()) {
					info("不是有效路径！");
					return;
				} 
				
				if (!file.exists()) { info("路径不存在！"); return;}
				
				String fileName = fileBean.getFilePath() + "\\"  + fileBean.getFuncName() + "-" + fileBean.getClusterName() 
						+ "-" + fileBean.getDsName() + "-" + fileBean.getParams() + "-" + format.format(new Date()) + ".xls";
				
				if (new File(fileName).exists()) 	file.delete();
				
				String path = file.getParent();
				
				if (StringUtils.isBlank(path)) { info("路径为空！"); return;}
				
				new DataExportOperator(fileName,headers).doData(cacheID, sql);

				flag = true;
				
			}
		};
		form.setOutputMarkupId(true);
		
		this.add(form);
		form.add(filePath);
		
		// button submit 
		form.add(new AjaxButton("export"){

			private static final long serialVersionUID = 1L;
			protected void onAfterSubmit(AjaxRequestTarget target, Form<?> form) {
				if (window != null  && flag)	window.close(target);
			}
		});
		
		// button cancel
		form.add(new AjaxLink<Void>("cancel"){
			
			private static final long serialVersionUID = 1L;
			public void onClick(AjaxRequestTarget target) {
				if (window != null)	window.close(target);
			}});
	}

}


